# app/schedule_search.py

from flask import Blueprint, request, jsonify, session, abort
from sqlalchemy import or_
from . import db
from .models import Schedule
from .schedule_mgmt import login_required  # reuse login_required decorator

search_bp = Blueprint('schedule_search', __name__, url_prefix='/api/schedules')

@search_bp.route('/search', methods=['GET'])
@login_required
def search_schedules():
    """
    GET /api/schedules/search?
      start_date=YYYY-MM-DD&
      end_date=YYYY-MM-DD&
      start_time=HH:MM&
      end_time=HH:MM&
      keyword=kw1&keyword=kw2&...
    返回符合条件的排课列表 JSON。
    """
    uid = session['user_id']
    q = Schedule.query.filter_by(user_id=uid)

    # 日期范围
    sd = request.args.get('start_date')
    ed = request.args.get('end_date')
    if sd:
        q = q.filter(Schedule.one_date >= sd)
    if ed:
        q = q.filter(Schedule.one_date <= ed)

    # 时间范围
    st = request.args.get('start_time')
    et = request.args.get('end_time')
    if st:
        q = q.filter(Schedule.start_time >= st)
    if et:
        q = q.filter(Schedule.end_time <= et)

    # 多关键字搜索
    for kw in request.args.getlist('keyword'):
        like = f"%{kw}%"
        q = q.filter(or_(
            Schedule.student_name.ilike(like),
            Schedule.course.ilike(like),
            Schedule.school.ilike(like)
        ))

    # 排序并构造返回数据
    results = []
    for s in q.order_by(Schedule.one_date, Schedule.start_time).all():
        results.append({
            "id": s.id,
            "one_date": s.one_date.strftime('%Y-%m-%d'),
            "weekday": s.one_date.strftime('%A'),
            "start_time": s.start_time.strftime('%H:%M'),
            "end_time": s.end_time.strftime('%H:%M'),
            "student_name": s.student_name
        })
    return jsonify(results), 200

@search_bp.route('/batch_delete', methods=['POST'])
@login_required
def batch_delete_schedules():
    """
    POST /api/schedules/batch_delete
    Body JSON: { "ids": [int, int, ...] }
    仅删除 status='未上' 且属于当前用户的那些记录。
    """
    uid = session['user_id']
    data = request.get_json() or {}
    ids = data.get('ids', [])
    if not isinstance(ids, list):
        return jsonify(error="ids 必须是一个列表"), 400

    # 只删除未上状态
    deleted = Schedule.__table__.delete().where(
        (Schedule.user_id == uid) &
        (Schedule.id.in_(ids)) &
        (Schedule.status == '未上')
    )
    db.session.execute(deleted)
    db.session.commit()
    return jsonify(message=f"已删除 {len(ids)} 条"), 200
